package cn.sczc.jh.client.controller.option;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.sczc.jh.client.base.AbstractController;
import cn.sczc.jh.client.entity.Equipment;
import cn.sczc.jh.client.entity.User;
import cn.sczc.jh.client.service.equipment.EquipmentService;
import cn.sczc.jh.client.util.DateUtil;
import cn.sczc.jh.client.util.DownloadExcelUtil;
import cn.sczc.jh.client.util.ExlVo;
import cn.sczc.jh.client.util.PageUtils;
import jxl.format.BorderLineStyle;

@Controller
@RequestMapping({ "/option/device" })
public class DeviceViewController extends AbstractController {
	@Autowired
	private EquipmentService equipmentService;
	
	@GetMapping()
	public String index(Model model) {
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		model.addAttribute("permissionList",user.getPermissions());
		model.addAttribute("userId", user.getId().toString());
		model.addAttribute("tenantId", user.getTenantId().toString());
		model.addAttribute("userName", user.getUsername());
		model.addAttribute("teamList", user.getTeams());
		return "option/device/maintenance";
	}
	
	@GetMapping("/list")
	@ResponseBody
	public ResponseEntity<?> list(@RequestParam Map<String, Object> params) {
		Map<String, Object> pageParams = new HashMap<>();
		pageParams.put("pageNum", params.get("pageNumber"));
		pageParams.put("pageSize", params.get("pageSize"));
		@SuppressWarnings("unchecked")
		Page<Equipment> page = (Page<Equipment>) super.getPage(pageParams);
		Page<Equipment> data = equipmentService.queryList(page,params);
		PageUtils pageUtil = new PageUtils(data.getRecords(), (int) data.getTotal());
		return ResponseEntity.ok(pageUtil);
	}
	
	@GetMapping("/pos")
	public String poslist(Model model) {
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		model.addAttribute("permissionList",user.getPermissions());
		model.addAttribute("userId", user.getId().toString());
		model.addAttribute("tenantId", user.getTenantId().toString());
		model.addAttribute("userName", user.getUsername());
		model.addAttribute("teamList", user.getTeams());
		return "option/device/equipmentPos";
	}

	@PostMapping("/save")
	@ResponseBody
	public ResponseEntity<?> save(@RequestBody Equipment entity) {
		Boolean result = equipmentService.insert(entity);
		return ResponseEntity.ok(result);
	}
	
	@PostMapping("/qryById/{id}")
	@ResponseBody
	public ResponseEntity<?> qryById(@PathVariable("id") String id) {
		Equipment s = equipmentService.qryById(id);
		return ResponseEntity.ok(s);
	}
	
	@PostMapping("/del/{id}")
	@ResponseBody
	public ResponseEntity<?> del(@PathVariable("id") String id) {
		Boolean result = equipmentService.del(id);
		return ResponseEntity.ok(result);
	}
	
	/**
	 * 安防物资数据导出
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "downLoadDeviceEXL")
	public String downLoadDeviceEXL(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//取出带查询条件的所有数据allList
		String p = request.getParameter("param").toString();
		String param = new String(p.getBytes("ISO8859-1"), "UTF-8");
		@SuppressWarnings("unchecked")
		Map<String, Object> params = JSON.parseObject(param, HashMap.class);
		List<Equipment> allList = equipmentService.queryListNoPage(params);
		if (allList!=null&&allList.size()>0) {
			//循环sheet
			DownloadExcelUtil dExlUtile = null;
			int dataNum = 1;
			for (Equipment item : allList) {
					//设置对象：title，value ，List<entity>
					StringBuffer sb = new StringBuffer();
					sb.append("*编号_");
					sb.append(item.getEquNo()!=null?item.getEquNo():"-");
					sb.append("$");
					sb.append("*设备类型_");
					sb.append(item.getEquType()!=null?item.getEquType():"0");
					sb.append("$");
					sb.append("*维保日期_");
					sb.append(item.getMaintenanceDate()!=null?DateUtil.format(item.getMaintenanceDate(), "yyyy-MM-dd"):"-");
					sb.append("$");
					sb.append("生产日期_");
					sb.append(item.getProductionDate()!=null?DateUtil.format(item.getProductionDate(), "yyyy-MM-dd"):"-");
					sb.append("$");
					sb.append("维保单位_");
					sb.append(item.getMaintenanceUnit()!=null?item.getMaintenanceUnit():"-");
					sb.append("$");
					sb.append("联系人_");
					sb.append(item.getContacts()!=null?item.getContacts():"-");
					sb.append("$");
					sb.append("联系电话_");
					sb.append(item.getContactPhone()!=null?item.getContactPhone():"-");
					sb.append("$");
					sb.append("备注_");
					sb.append(item.getRemarks()!=null?item.getRemarks():"-");
					sb.append("$");
					sb.append("状态_");
					sb.append(item.getState()!=null?item.getState():"-");
					String tvsb = sb.toString();
					String[] tvsbArray = tvsb.split("\\$");
					List<ExlVo> entityList = new ArrayList<ExlVo>();
					if (tvsbArray.length>0) {
						for (String tv : tvsbArray) {
							ExlVo entity = new ExlVo();
							String[] tvArray = tv.split("_");
							entity.setTitle(tvArray[0]);
							entity.setValue(tvArray.length==1?"-":tvArray[1]);
							entityList.add(entity);
						}
					}
					if (dataNum == 1) {//若为第一次循环
						//在response中写入exl。传入当前type的name，和文件名：DownloadExcelUtil
						dExlUtile = new DownloadExcelUtil(response,"设备维保信息数据","设备维保信息数据");
						//把list<entity>中的title按list的顺序放入String【】，调用：setExcelListTitle
						String[] titleArray = new String[entityList.size()];
						for (int i = 0; i < entityList.size(); i++) {
							titleArray[i] = entityList.get(i).getTitle();
						}
						dExlUtile.addRow(titleArray, BorderLineStyle.THIN,jxl.format.Alignment.CENTRE, "bold");
						//dExlUtile.setExcelListTitle(titleArray);
						//把list<entity>中的value按list的顺序放入String【】，调用：addRow
						String[] valueArray = new String[entityList.size()];
						for (int i = 0; i < entityList.size(); i++) {
							valueArray[i] = entityList.get(i).getValue();
						}
						dExlUtile.addRow(valueArray, BorderLineStyle.THIN,jxl.format.Alignment.CENTRE, "");
					}else {
						//把list<entity>中的value按list的顺序放入String【】，调用：addRow
						String[] valueArray = new String[entityList.size()];
						for (int i = 0; i < entityList.size(); i++) {
							valueArray[i] = entityList.get(i).getValue();
						}
						dExlUtile.addRow(valueArray, BorderLineStyle.THIN,jxl.format.Alignment.CENTRE, "");
					}									
					dataNum++;
			}
		          dExlUtile.reportExcel();
			
		}else {
			//查询结果为空
		}
		return null;
	}
	
}
